package com.hzcx.app.simplechat.ui.chat;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hyphenate.chat.EMImageMessageBody;
import com.hyphenate.chat.EMMessage;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.common.Common;
import com.hzcx.app.simplechat.ui.chat.adapter.ChatCollectAdapter;
import com.hzcx.app.simplechat.ui.chat.bean.ChatCollectBean;
import com.hzcx.app.simplechat.ui.chat.contract.ChatCollectContract;
import com.hzcx.app.simplechat.ui.chat.dialog.ChatCollectDialog;
import com.hzcx.app.simplechat.ui.chat.event.ChatCollectEvent;
import com.hzcx.app.simplechat.ui.chat.presenter.ChatCollectPresenter;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import eason.linyuzai.download.ELoad;
import eason.linyuzai.download.recycle.TaskRecycler;
import eason.linyuzai.download.task.DownloadTask;
import io.reactivex.Observable;
import okhttp3.ResponseBody;

/**
 * 收藏界面
 */
public class ChatCollectActivity extends BaseActivity<ChatCollectPresenter> implements ChatCollectContract.View, OnRefreshListener,
        BaseQuickAdapter.RequestLoadMoreListener {

    public static final String INTENT_HEAD="INTENT_HEAD";
    public static final String INTENT_NICKNAME="INTENT_NICKNAME";

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.rv_collect)
    RecyclerView rvCollect;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;

    private List<ChatCollectBean> collectData;
    private ChatCollectAdapter collectAdapter;
    private int page;
    private boolean isRefresh = true;

    @Override
    public int getLayout() {
        return R.layout.activity_chat_collect;
    }

    @Override
    public void initPresenter() {
        mPresenter = new ChatCollectPresenter();
    }

    @Override
    public void initView() {

        tvTitle.setText("收藏");

        collectData = new ArrayList<>();
        collectAdapter = new ChatCollectAdapter(collectData);
        rvCollect.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        rvCollect.setAdapter(collectAdapter);

        smartRefresh.setOnRefreshListener(this);
        collectAdapter.setOnLoadMoreListener(this);

    }

    @Override
    public void initData() {

        smartRefresh.autoRefresh();

        collectAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()) {
                case R.id.tv_delete: // 删除收藏
                    mPresenter.deleteChatCollect(ChatCollectActivity.this, collectData.get(position).getCollect_id(), position);
                    break;

                case R.id.cons_content: // 列表点击
                    showCollectDialog(position);
                    break;
            }
        });

        collectAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });
    }

    /**
     *  弹出发送收藏弹窗
     * @param pos
     */
    private void showCollectDialog(int pos){
        ChatCollectDialog collectDialog=new ChatCollectDialog(this, getIntent().getStringExtra(INTENT_HEAD), getIntent().getStringExtra(INTENT_NICKNAME),
                collectData.get(pos).getCollectdetail(), collectData.get(pos).getCollectimage(), new ChatCollectDialog.OnChatCollectListener() {
            @Override
            public void sendCollect(String remark) {
                sendCollectMsg(pos,remark);
            }
        });
        collectDialog.show();
    }

    /**
     *  发送收藏
     * @param pos
     * @param remark
     */
    private void sendCollectMsg(int pos,String remark){
        if(EmptyUtils.isEmpty(collectData.get(pos).getCollectimage())){
            // 发送文本收藏
            EventBus.getDefault().post(new ChatCollectEvent(collectData.get(pos).getCollectdetail(),null,remark));
            showError("发送成功");
        }else {
            // 发送图片收藏，需要先下载图片到本地
            downLoadChatImg(collectData.get(pos).getCollectimage(),remark);
        }
    }

    /**
     * 下载聊天图片
     */
    private void downLoadChatImg(String url, String remark) {
        showLoading();
        //可以当成Http Client
        ELoad eload = new ELoad.Builder(this)
                .addDownloadTaskListener(new DownloadTask.DownloadTaskListener() {
                    @Override
                    public void onDownloadTaskPrepare(DownloadTask task, Observable<ResponseBody> observable) {

                    }

                    @Override
                    public void onDownloadTaskStart(DownloadTask task) {

                    }

                    @Override
                    public void onDownloadTaskPause(DownloadTask task) {

                    }

                    @Override
                    public void onDownloadTaskResume(DownloadTask task) {

                    }

                    @Override
                    public void onDownloadTaskError(DownloadTask task, Throwable e) {
                        LogUtils.d("下载错误:" + e.getMessage());
                        hideLoading();
                    }

                    @Override
                    public void onDownloadTaskComplete(DownloadTask task) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                String path = task.getEntity().getFilePath() + "/" +
                                        task.getEntity().getFileName();
                                LogUtils.d("下载完成：" + path);
                                hideLoading();
                                EventBus.getDefault().post(new ChatCollectEvent(null,path,remark));
                                showError("发送成功");
                            }
                        });
                    }

                    @Override
                    public void onDownloadTaskCancel(DownloadTask task) {

                    }

                    @Override
                    public void onDownloadTaskReset(DownloadTask task) {

                    }

                    @Override
                    public void onDownloadTaskRecycle(DownloadTask task, TaskRecycler taskRecycler) {

                    }
                }).build();
        //可以当成一个Request
        DownloadTask task = eload.url(url).create();
        task.start();
    }

    /**
     * 收藏列表获取成功
     *
     * @param data
     */
    @Override
    public void collectListResult(List<ChatCollectBean> data) {
        smartRefresh.finishRefresh();
        collectAdapter.loadMoreComplete();
        try {
            if (isRefresh) {
                collectData.clear();
            }
            collectData.addAll(data);
            collectAdapter.notifyDataSetChanged();
            if (data.size() < Common.PAGE_COUNT) {
                collectAdapter.loadMoreEnd();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFail() {
        smartRefresh.finishRefresh();
        collectAdapter.loadMoreFail();
    }

    /**
     * 收藏删除成功
     *
     * @param pos
     */
    @Override
    public void deleteSuccess(int pos) {
        collectData.remove(pos);
        collectAdapter.notifyDataSetChanged();
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMoreRequested() {
        page++;
        isRefresh = false;
        mPresenter.getChatCollectList(this, page);
    }

    /**
     * 刷新
     *
     * @param refreshLayout
     */
    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        isRefresh = true;
        mPresenter.getChatCollectList(this, page);
    }
}
